#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "global_var.h"

unsigned char g_log_file_path[128];
char g_hostname[128];
char g_hostdomain[128];
char g_ipv4_addr[16];
char g_ipv6_addr[48];
short g_port;
sqlite3 *g_config_db;
short g_handle_threads_num;
short g_accept_threads_num;
short g_output_threads_num;
size_t g_max_mail_size;

void init_global_var(int argc, char **argv)
{
	if (argc < 2 || init_config_db(argv[1], &g_config_db) != 0)
	{
		fprintf(stderr, "Unable to open config db file!");
		exit(0);
	}
	int r = 0;

	r |= get_config_var(g_config_db, "log_file_path", g_log_file_path, 128);
	r |= get_config_var(g_config_db, "hostname", g_hostname, 128);
	r |= get_config_var(g_config_db, "hostdomain", g_hostdomain, 128);
	r |= get_config_var(g_config_db, "ipv4_address", g_ipv4_addr, 16);
	r |= get_config_var(g_config_db, "ipv6_address", g_ipv6_addr, 48);

	unsigned char p[32] = {0};

	r |= get_config_var(g_config_db, "port", p, 32);
	if (r == 0)
		g_port = atoi(p);
	else
		r = 1;

	memset(p, 0, sizeof(unsigned char) * 32);
	r |= get_config_var(g_config_db, "handle_threads_num", p, 32);
	if (r == 0)
		g_handle_threads_num = atoi(p);
	else
		r = 1;

	memset(p, 0, sizeof(unsigned char) * 32);
	r |= get_config_var(g_config_db, "accept_threads_num", p, 32);
	if (r == 0)
		g_accept_threads_num = atoi(p);
	else
		r = 1;

	memset(p, 0, sizeof(unsigned char) * 32);
	r |= get_config_var(g_config_db, "output_threads_num", p, 32);
	if (r == 0)
		g_output_threads_num = atoi(p);
	else
		r = 1;

	memset(p, 0, sizeof(unsigned char) * 32);
	r |= get_config_var(g_config_db, "max_mail_size", p, 32);
	if (r == 0)
		g_max_mail_size = atoll(p);
	else
		r = 1;

	if (r != 0)
	{
		fprintf(stderr, "Reading config db file error!");
		exit(0);
	}
}